<?php

namespace app\admin\model;

use think\db\exception\DbException;
use think\Model;

/**
 * OrderGoodsRefund
 * @controllerUrl 'orderGoodsRefund'
 */
class OrderGoodsRefund extends Model
{
    // 表名
    protected $name = 'order_goods_refund';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';

    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';


    public function getOrderGoodsIdAttr($value, $row)
    {
        return !$value ? '' : $value;
    }

    public function getImagesAttr($value, $row)
    {
        if ($value == '') {
            return [];
        }
        if (!is_array($value)) {
            return explode(',', $value);
        }
        return $value;
    }

    public function setImagesAttr($value, $row)
    {
        if ($value && is_array($value)) {
            return implode(',', $value);
        }
        return $value ? $value : '';
    }

    /**
     * 获取唯一订单号
     * @return string
     * @throws DbException
     */
    public function getOrderSn(): string
    {
        try {
            [$micro, $time] = explode(' ', microtime());
            $micro = explode('.', sprintf('%.6f', $micro));
            $micro = $micro[1];
        } catch (\Exception $e) {
            $micro = rand(100000, 999999);
        }
        $orderSn = date('YmdHis') . $micro . rand(1000, 9999);
        $hasSn = $this->where('refund_sn', $orderSn)->count();
        if ($hasSn > 0) {
            return $this->getOrderSn();
        }
        return $orderSn;
    }

    public function orderGoods()
    {
        return $this->hasOne(OrderGoods::class, 'id', 'order_goods_id');
    }
}